//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package net.mingsoft.mdiy.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapWrapper;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.StringTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.core.ParseException;
import freemarker.core.TemplateClassResolver;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Clob;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.SpringUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.config.MSProperties;
import net.mingsoft.mdiy.biz.ITagBiz;
import net.mingsoft.mdiy.constant.e.TagTypeEnum;
import net.mingsoft.mdiy.entity.TagEntity;
import net.mingsoft.mdiy.tag.CustomTag;
import net.mingsoft.mdiy.tag.IncludeExTag;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

public class ParserUtil {
    protected static final Logger LOG = LoggerFactory.getLogger(ParserUtil.class);
    public static final String SHORT_SWITCH = "shortSwitch";
    public static final String HTML = "html";
    public static final String INDEX = "index";
    public static final String HTML_SUFFIX = ".html";
    public static final String TAG_PREFIX = "ms_";
    public static final String PAGE_LIST = "list-";
    public static final String HTM_SUFFIX = ".htm";
    public static final String IS_DO = "isDo";
    public static final String URL = "url";
    public static final String COLUMN = "column";
    public static final String ID = "id";
    public static final String FIELD = "field";
    public static final String TABLE_NAME = "tableName";
    public static final String MODEL_NAME = "modelName";
    public static final String PAGE = "pageTag";
    public static final String TYPE_ID = "typeid";
    public static final String APP_ID = "appId";
    public static final String APP_DIR = "appDir";
    public static Configuration cfg;
    public static FileTemplateLoader ftl;
    public static StringTemplateLoader stringLoader;
    public static List<String> systemTag1;
    public static final Lock LOCK;
    public static final String CONTEXT_PATH = "contextPath";

    public ParserUtil() {
    }

    public static String buildTemplatePath() {
        return buildTemplatePath((String)null);
    }

    public static String buildTemplatePath(String path) {
        return buildTemplatePath((String)null, path);
    }

    public static String buildTemplatePath(String style, String path) {
        String uploadTemplatePath = MSProperties.upload.template;
        return BasicUtil.getWebsiteApp() != null ? BasicUtil.getRealPath(uploadTemplatePath + File.separator + BasicUtil.getWebsiteApp().getAppId() + File.separator + (style != null ? File.separator + style : BasicUtil.getWebsiteApp().getAppStyle()) + (path != null ? File.separator + path : "")) : BasicUtil.getRealPath(uploadTemplatePath + File.separator + BasicUtil.getApp().getAppId() + File.separator + (style != null ? File.separator + style : BasicUtil.getApp().getAppStyle()) + (path != null ? File.separator + path : ""));
    }

    public static String buildHtmlPath(String path, String htmlDir, String appDir) {
        return BasicUtil.getRealPath(htmlDir) + File.separator + appDir + File.separator + path + ".html";
    }

    public static String rendering(Map root, String content) throws IOException, TemplateException {
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        stringLoader.putTemplate("template", content);
        cfg.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
        cfg.setNumberFormat("#");
        cfg.setTemplateLoader(stringLoader);
        cfg.setSharedVariable("MUtil", new MUtil());
        Template template = cfg.getTemplate("template", "utf-8");
        StringWriter writer = new StringWriter();
        template.process(root, writer);
        return writer.toString();
    }

    public static int getPageSize(String templatePath, int defaultSize) {
        String buildTempletPath = buildTemplatePath();
        String content = FileUtil.readString(FileUtil.file(buildTempletPath, templatePath), CharsetUtil.CHARSET_UTF_8);
        Pattern pattern = Pattern.compile("\\{(.*?)ispaging=true(.*?)\\}");
        Matcher m = pattern.matcher(content);
        String size = null;
        if (m.find()) {
            size = ReUtil.extractMulti("size=(\\d*)", m.group(1), "$1");
            if (size == null) {
                size = ReUtil.extractMulti("size=(\\d*)", m.group(2), "$1");
            }

            if (size != null) {
                defaultSize = Integer.parseInt(size);
            }

            LOG.debug("获取分页的size:{}", size);
        }

        return defaultSize;
    }

    public static String rendering(String templatePath, Map map) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
        LOCK.lock();

        try {
            String buildTempletPath = buildTemplatePath();
            ITagBiz tagBiz = (ITagBiz)SpringUtil.getBean(ITagBiz.class);
            List<TagEntity> list = tagBiz.list();
            if (ftl == null || !buildTempletPath.equals(ftl.baseDir.getPath())) {
                stringLoader = new StringTemplateLoader();
                ftl = new FileTemplateLoader(new File(buildTempletPath));
                MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(new TemplateLoader[]{stringLoader, ftl});
                cfg.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
                cfg.setNumberFormat("#");
                cfg.setTemplateLoader(multiTemplateLoader);
                cfg.setSharedVariable("MUtil", new MUtil());
                ClassPathResource classPathResource = new ClassPathResource("WEB-INF/macro.ftl");
                String template = IOUtils.toString(classPathResource.getInputStream(), "UTF-8");
                StringBuffer sb = new StringBuffer(template);
                list.forEach((tag) -> {
                    TagTypeEnum typeEnum = TagTypeEnum.get(tag.getTagType());
                    if (typeEnum == TagTypeEnum.MACRO) {
                        sb.append(tag.getTagSql());
                    }

                });
                stringLoader.putTemplate("macro.ms", sb.toString());
                cfg.setClassicCompatible(true);
                cfg.addAutoInclude("macro.ms");
            }

            String temp = FileUtil.readString(FileUtil.file(buildTempletPath, templatePath), CharsetUtil.CHARSET_UTF_8);
            Template template = null;
            temp = replaceTag(temp);
            stringLoader.putTemplate("ms:custom:" + templatePath, temp);

            try {
                template = cfg.getTemplate("ms:custom:" + templatePath, "utf-8");
            } catch (Exception var13) {
                LOG.debug("模板错误");
                var13.printStackTrace();
                LOG.debug(temp);
            }

            cfg.setClassicCompatible(true);
            cfg.setSharedVariable("ms_includeEx", new IncludeExTag(buildTempletPath, stringLoader));
            list.forEach((tag) -> {
                if (StrUtil.isNotBlank(tag.getTagName())) {
                    TagTypeEnum typeEnum = TagTypeEnum.get(tag.getTagType());
                    if (typeEnum == TagTypeEnum.LIST) {
                        cfg.setSharedVariable("ms_" + tag.getTagName(), new CustomTag(map, tag));
                    }

                    if (typeEnum == TagTypeEnum.SINGLE && (!systemTag1.contains(tag.getTagName()) || map.containsKey("id") && tag.getTagName().equals("field") || map.containsKey("pageTag") && (tag.getTagName().equals("pre") || tag.getTagName().equals("next") || tag.getTagName().equals("page")))) {
                        String sql = null;

                        try {
                            sql = rendering(map, tag.getTagSql());
                            List _list = (List)tagBiz.excuteSql(sql);
                            if (_list.size() > 0) {
                                if (_list.get(0) != null) {
                                    MapWrapper<String, Object> mw = new MapWrapper((HashMap)_list.get(0));
                                    mw.forEach((x) -> {
                                        if (x.getValue() instanceof Clob) {
                                            x.setValue(StringUtil.clobStr((Clob)x.getValue()));
                                        }

                                    });
                                }

                                map.put(tag.getTagName(), _list.get(0));
                            }
                        } catch (IOException var7) {
                            LOG.error("", var7);
                        } catch (TemplateException var8) {
                            LOG.error("", var8);
                        }
                    }
                }

            });
            StringWriter writer = new StringWriter();
            template.process(map, writer);
            String var19 = writer.toString();
            return var19;
        } catch (Exception var14) {
            LOG.error("渲染错误", var14);
            var14.printStackTrace();
        } finally {
            LOCK.unlock();
        }

        return null;
    }

    public static String replaceTag(String content) {
        content = content.replaceAll("<#include(.*)/>", StrUtil.format("<@{}includeEx template=$1/>", new Object[]{"ms_"}));
        content = content.replaceAll("<#include(.*)>", StrUtil.format("<@{}includeEx template=$1/>", new Object[]{"ms_"}));
        content = content.replaceAll("\\{ms:([^\\}]+)/\\}", "\\${$1}");
        content = content.replaceAll("\\{@ms:([^\\}]+)/\\}", StrUtil.format("<@{}$1/>", new Object[]{"ms_"}));
        content = content.replaceAll("\\{ms:([^\\}]+)\\}", StrUtil.format("<@{}$1>", new Object[]{"ms_"}));
        content = content.replaceAll("\\{/ms:([^\\}]+)\\}", StrUtil.format("</@{}$1>", new Object[]{"ms_"}));
        content = content.replaceAll("\\[([^\\]]+)/\\]", "\\${$1}");
        return content;
    }

    static {
        cfg = new Configuration(Configuration.VERSION_2_3_0);
        ftl = null;
        systemTag1 = CollUtil.toList(new String[]{"field", "pre", "page", "next"});
        LOCK = new ReentrantLock();
    }
}
